<template>
    <div>
        <div class="container">
            <div class="handle-box">
                <div>
                    <el-input v-model="query.keywords" placeholder="关键词" class="handle-input mr10"></el-input>
                    <!-- <el-select v-if="departs.length > 1" v-model="query.depart" class="m-2 mr10" placeholder="请选择部门"
                        size="large">
                        <el-option key="0" label="全部部门" value="0" />
                        <el-option v-for="depart in departs" :key="depart.depart_id" :label="depart.depart_name"
                            :value="depart.depart_id" />
                    </el-select> -->
                    <el-select v-model="query.type" class="m-2 mr10" placeholder="请选择类型" size="large">
                        <el-option key="0" label="全部类型" value="0" />
                        <el-option v-for="item in types" :key="item.id" :label="item.dic_vlu" :value="item.dic_key" />
                    </el-select>
                    <el-date-picker class="ml10 mr10" v-model="query.date" type="daterange" unlink-panels
                    range-separator="到" start-placeholder="开始日期" end-placeholder="结束日期" value-format="YYYY-MM-DD" />

                    <el-button type="primary" class="m-2" size="small" icon="el-icon-search"
                        @click="handleSearch">搜索</el-button>
                </div>
                <div>
                    <!-- <el-button type="primary" size="small" icon="el-icon-plus" @click="handleCreate" class="add-btn">
                        添加扫码</el-button> -->
                </div>
            </div>
            <el-table :data="tableData" border class="table" ref="multipleTable" header-cell-class-name="table-header"
                :cell-style="{padding:'3px 0'}">
                <el-table-column prop="scan_id" label="ID" width="55" align="center"></el-table-column>
                <el-table-column prop="scan_value" label="条码值"></el-table-column>
                <el-table-column prop="scan_time" width="170" label="扫码时间"></el-table-column>
                <el-table-column prop="bar_type" label="类型">
                    <template #default="scope">{{ getAdviceType(scope.row.bar_type) }}</template>
                </el-table-column>
                <el-table-column prop="device_type" label="设备类型"></el-table-column>
                <el-table-column prop="device_id" label="设备ID"></el-table-column>

                <el-table-column prop="scan_value" label="扫码值"></el-table-column>
                <el-table-column prop="bar_rtn1" label="扫码返回值1"></el-table-column>
                <el-table-column prop="bar_rtn2" label="扫码返回值2"></el-table-column>
                <el-table-column prop="bar_rtn3" label="扫码返回值3"></el-table-column>
                <el-table-column prop="bar_rtn4" label="扫码返回值4"></el-table-column>
                <el-table-column prop="bar_rtn5" label="扫码返回值5"></el-table-column>

                <el-table-column prop="operate_id" label="操作者ID"></el-table-column>
                <el-table-column prop="operate_name" label="操作者姓名"></el-table-column>
                <el-table-column prop="operate_id_his" label="操作者HISID"></el-table-column>

            </el-table>
            <div class="pagination">
                <el-pagination background layout="total, prev, pager, next" :current-page="query.page"
                    :page-size="query.limit" :total="pageTotal" @current-change="handlePageChange"></el-pagination>
            </div>
        </div>

        <!-- 添加弹出框 -->
        <el-dialog title="添加" v-model="addVisible" width="50%">
            <el-form label-width="110px">
                <el-form-item label="扫码值">
                    <el-input v-model="createForm.scan_value"></el-input>
                </el-form-item>
                <el-form-item label="扫码类型">
                    <el-input v-model="createForm.scan_type"></el-input>
                </el-form-item>

                <!-- <el-form-item label="扫码类型">
                    <el-select v-model="createForm.scan_type" class="m-2" placeholder="请选择扫码类型" size="large"
                        @change="typeChange">
                        <el-option v-for="item in types" :key="item.id" :label="item.dic_vlu" :value="item.dic_vlu" />
                    </el-select>
                </el-form-item> -->
                <!-- <el-form-item label="测量子类型" v-if="createForm.scan_type > 0">
                    <el-select v-model="createForm.scan_type_son" class="m-2" placeholder="请选择扫码类型" size="large">
                        <el-option v-for="item in getSonType(createForm.scan_type)" :key="item.id" :label="item.title"
                            :value="item.id" />
                    </el-select>
                </el-form-item> -->
                <el-form-item label="操作者">
                    <el-select v-model="createForm.operate_id" class="m-2" placeholder="请选择操作者" size="large">
                        <el-option v-for="item in staffs" :key="item.staff_id" :label="item.staff_name"
                            :value="item.staff_id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="患者">
                    <el-select v-model="createForm.bed_id" class="m-2" placeholder="请选择患者" size="large">
                        <el-option v-for="item in beds" :key="item.bed_id"
                            :label="`${item.depart_name}病区-${item.bed_room}房-${item.bed_name}床-${item.hz_name}`"
                            :value="item.bed_id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="测量值">
                    <el-input v-model="createForm.vital_val"></el-input>
                </el-form-item>
                <el-form-item label="测量值单位">
                    <el-input v-model="createForm.vital_unit"></el-input>
                </el-form-item>
                <el-form-item label="测量值子项1">
                    <el-input v-model="createForm.vital_val_son1"></el-input>
                </el-form-item>
                <el-form-item label="测量值子项2">
                    <el-input v-model="createForm.vital_val_son2"></el-input>
                </el-form-item>

            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="addVisible = false">取 消</el-button>
                    <el-button type="primary" @click="saveCreate">确 定</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 编辑弹出框 -->
        <el-dialog title="编辑" v-model="editVisible" width="50%">
            <el-form label-width="70px">
                <el-form-item label="账号名称">
                    <el-input v-model="eidtForm.info.name"></el-input>
                </el-form-item>
                <el-form-item label="账号密码">
                    <el-input v-model="eidtForm.info.password"></el-input>
                </el-form-item>
                <el-form-item label="确认密码">
                    <el-input v-model="eidtForm.info.apassword"></el-input>
                </el-form-item>
                <el-form-item label="显示名称">
                    <el-input v-model="eidtForm.info.showname"></el-input>
                </el-form-item>
                <el-form-item label="管理员 ">
                    <el-radio-group v-model="eidtForm.info.isadmin" class="ml-4">
                        <el-radio label="1" size="large">是</el-radio>
                        <el-radio label="0" size="large">否</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="editVisible = false">取 消</el-button>
                    <el-button type="primary" @click="saveEdit">确 定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script>
    import { ref, reactive } from "vue";
    import { ElMessage, ElMessageBox } from "element-plus";
    import { staffAll, bedAll, scanList, scanCreate, scanUpdate, dictBarType } from "../api/index";
    import { typeName, log, getUserInfo } from "../utils/user"

    export default {
        name: "basetable",
        setup() {
            const statusText = ["禁用", "启用"]
            const typeNames = typeName();

            let typeText = {};
            Object.keys(typeNames).forEach(k => {
                typeText[typeNames[k][0]] = typeNames[k][1]
            })
            log("typeText", typeText);

            const query = reactive({
                keywords: "",
                depart: '0',
                date:[],
                type: '0',
                page: 1,
                limit: 15,
            });

            let user = getUserInfo();
            const departs = ref([]);

            const adviceTypes = ref([])

            const tableData = ref([]);
            const pageTotal = ref(0);

            // 获取表格数据
            const getData = () => {
                scanList(query).then((res) => {
                    if (res.status == 'ok') {
                        adviceTypes.value =  res.data.type
                        tableData.value = res.data.list.list;
                        pageTotal.value = res.data.list.pageTotal || 1;

                        if (departs.value.length == 0) {
                            if (user.is_admin == '0') {
                                let allDeparts = user.manage_departs ? user.manage_departs.split(',') : []
                                res.data.depart.forEach(depart => {
                                    if (allDeparts.indexOf(depart.depart_id + '') > -1) {
                                        departs.value.push(depart)
                                    }
                                })
                            } else {
                                departs.value = res.data.depart
                            }
                        }
                    } else {
                        ElMessage.error(res.msg)
                        return false;
                    }
                });
            };
            getData();


            // 查询操作
            const handleSearch = () => {
                query.page = 1;
                getData();
            };
            // 分页导航
            const handlePageChange = (val) => {
                query.page = val;
                getData();
            };

            // 删除操作
            const handleDelete = (index) => {
                // 二次确认删除
                ElMessageBox.confirm("确定要删除吗？", "提示", {
                    type: "warning",
                })
                    .then(() => {
                        ElMessage.success("删除成功");
                        tableData.value.splice(index, 1);
                    })
                    .catch(() => { });
            };
            const staffs = ref([]);
            const beds = ref([]);
            // 表格添加
            const addVisible = ref(false);

            const handleCreate = () => {
                if (staffs.value.length == 0) {
                    staffAll({}).then(res => {
                        if (res.status == 'ok') {
                            staffs.value = res.data;
                            if (beds.value.length > 0) {
                                addVisible.value = true;
                            }
                        } else {
                            ElMessage.error(res.msg)
                            return false;
                        }
                    })
                }
                if (beds.value.length == 0) {
                    bedAll({}).then(res => {
                        if (res.status == 'ok') {
                            beds.value = res.data;
                            if (staffs.value.length > 0) {
                                addVisible.value = true;
                            }
                        } else {
                            ElMessage.error(res.msg)
                            return false;
                        }
                    })
                }
                if (staffs.value.length > 0 && beds.value.length > 0) {
                    addVisible.value = true;
                }
            };
            const types = ref([])
            const getTypeData = () => {
                dictBarType({}).then(res => {
                    if (res.status == 'ok') {
                        types.value = res.data
                    }
                })
            };
            getTypeData()
            const getType = id => {
                let type = types.find(v => v.dic_id == id)
                return type.dic_vlu
            }

            const typeChange = () => {
                createForm.scan_type_son = ''
            }

            let createForm = reactive({
                scan_value: "",
                scan_type: "",
                scan_type_son: "",
                operate_id: "",
                bed_id: "",
                vital_val: "",
                vital_unit: "",
                vital_val_son1: "",
                vital_val_son2: "",
            });

            const saveCreate = () => {
                log(createForm)
                if (!createForm.scan_value) {
                    ElMessage.error('请输入扫码值')
                    return false;
                }

                scanCreate(createForm).then(res => {
                    if (res.status == 'ok') {
                        addVisible.value = false;
                        ElMessage.success(res.msg);
                        query.pageIndex = 1;
                        getData();
                    } else {
                        ElMessage.error(res.msg)
                    }
                })
            }


            // 表格编辑时弹窗和保存
            const editVisible = ref(false);
            let eidtForm = reactive({
                id: 0,
                info: {
                    name: "",
                    password: "",
                    apassword: "",
                    showname: "",
                    isadmin: "0",
                }
            });
            let idx = -1;
            const handleEdit = (index, row) => {
                idx = index;
                eidtForm.info.name = row["account_name"];
                eidtForm.info.password = row["account_pwd"];
                eidtForm.info.showname = row["show_name"];
                eidtForm.info.isadmin = row["is_admin"] + '';
                eidtForm.id = row["id"];
                editVisible.value = true;
            };
            const saveEdit = () => {
                if (!eidtForm.info.name) {
                    ElMessage.error('请输入账号')
                    return false;
                }
                if (!eidtForm.info.password) {
                    ElMessage.error('请输入密码')
                    return false;
                }
                if (eidtForm.info.password != eidtForm.info.apassword) {
                    ElMessage.error('请确认输入密码')
                    return false;
                }
                accountUpdate(eidtForm).then(res => {
                    if (res.status == 'ok') {
                        editVisible.value = false;
                        ElMessage.success(res.msg);
                        getData();
                    } else {
                        ElMessage.error(res.msg)
                    }
                })

            };
            const toggleStatus = (id, status) => {
                log("toggleStatus", id)
                let temp = {
                    id: id,
                    info: {
                        status: status
                    }
                }

                ElMessageBox.confirm("确认修改吗", "提示", {
                    type: "warning",
                })
                    .then(() => {
                        accountUpdate(temp).then(res => {
                            if (res.status == 'ok') {
                                ElMessage.success(res.msg)
                                getData();
                                return false;
                            } else {
                                ElMessage.error(res.msg)
                                return false;
                            }
                        })
                    })
                    .catch(() => { });


            }
            const handleType = [
                {
                    id: "0",
                    title: '未处理'
                },
                {
                    id: "1",
                    title: '调用barcode表'
                },
                {
                    id: "2",
                    title: '写入第三方库'
                },
            ]
            const getHandleType = id => {
                let type = handleType.find(v => v.id == id)
                return type.title
            }
            const getAdviceType = id => {
                let advice = adviceTypes.value.find(v => v.dic_key == id);
                return advice ? advice.dic_vlu : id
            }

            return {
                statusText,
                typeText,

                // data
                query,
                tableData,
                pageTotal,


                handleSearch,
                handlePageChange,
                handleDelete,

                editVisible,
                eidtForm,
                handleEdit,
                saveEdit,

                createForm,
                addVisible,
                handleCreate,
                saveCreate,

                toggleStatus,
                types,
                getType,
                staffs,
                beds,
                getHandleType,
                departs,
                getAdviceType
            };
        },
    };
</script>

<style scoped>
    .handle-box {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 8px;
    }

    .handle-input {
        width: 300px;
        display: inline-block;
    }

    .table {
        width: 100%;
        font-size: 14px;
    }

    .red {
        color: #ff0000;
    }

    .mr10 {
        margin-right: 10px;
    }

    .table-td-thumb {
        display: block;
        margin: auto;
        width: 40px;
        height: 40px;
    }

    .m-radio {
        margin: 12px;
    }
</style>